<?php
/**
 * Created by 张彪.
 * User: 小马出行
 * Date: 2017/10/26
 * Time: 13:51
 */
namespace app\api\logic;

use app\api\model\DriverModel;
use app\api\model\OrderModel;
use app\api\model\TripModel;

use app\api\model\WalletModel;
use think\Model;
use my\Define;
use my\Security;
use my\Local;
use think\Cache;

class TripLogic Extends Model
{

    /**
     * 通过订单id获取订单信息
     * @param $id
     * @param $string
     * @return false|\PDOStatement|string|\think\Collection
     * */
    public function getTripById($id,$string)
    {
        $tripRecord = new OrderModel();
        return $tripRecord->getOrderById($id,$string);
    }

	/**
	 * 通过司机id或乘客端id获取已完成订单信息
	 * @param $did
	 * @param $string
	 * @param $p
	 * @param $limit
	 * @param $status,1为司机2乘客
	 * @return false|\PDOStatement|string|\think\Collection
	 * */
	public function getTripDoneByDid($did,$string,$p,$limit=10,$status = 1)
	{
		$tripRecord = new OrderModel();
		$map['order_status'] = array('in',array(40,45,50));
		if($status == 2){
			$map["uid"] = $did;
		}else{
			$map["driver_id"] = $did;
		}
		return $tripRecord->getOrderList($string,$map,$p,$limit);
	}

    /**
    * 通过司机id获取总行程
    * @param $did
    * @return string
    * */
    public function getTripTotalDisByDid($did)
    {
        $total = new OrderModel();
        $type = 'driver';
        return $total->getTotalDisByXid($did,$type);
    }


    /**
     * 客户到达目的地
     * @param $id
     * @param $common_id
     * @param $off_local //下车坐标
     * @param $direction //行驶方向
     * @param $order_type //订单类型 1为出租车，2为网约车
     * @return array
     * */
    public function sureTripDone($id,$common_id,$off_local,$order_type,$direction)
    {
        $actual = Local::getPlace($off_local);
        if ($actual['status'] == 0) {
            return array("status" => 20,'msg'=>'到达定位解析错误');//实际地址解析错误
        }
        $orderModel = new OrderModel();
        $field = 'local_table,zone_price,coupon_price,every_price,first_price,red_price,
        order_status,start_local,start_name,arrive_local,arrive_name,on_car_time';
        $order = $orderModel->getOrderById($common_id,$field);
        if($order['order_status']==30){
            $data = $this->saveOff($id,$common_id,$off_local,$order['local_table'],$order['zone_price'],$order_type,$direction);
            if(array_key_exists('status',$data)&&$data['status']==10){
                return array('status'=>10,'msg'=>'距离计算出现错误');//距离计算出现错误
            }
            $data['off_car_time'] = $data_dd['created_at'] = $data_pay_log ['off_car_time'] = time();
            $data['order_status'] = 40;
            $data['actual_local'] = Security::encrypt($off_local);
            $data['actual_name'] = Security::encrypt($actual['province'].$actual['city'].$actual['district'].$actual['place_name']);
            if($order_type==1){
                $data['need_price'] = $data['original_price']-$order['coupon_price']-$order['every_price'] -$order['first_price']-$order['red_price'];
            }
            db('order_common')->where('common_id='.$common_id)->update($data);
            /*--------保存司机本单行驶距离--------*/
            $data_dd['driver_id'] = $id;
            $data_dd['order_id'] = $common_id;
            $data_dd['distance'] = $data['real_distance'];
            db('driver_distance')->insert($data_dd);//保存本单司机行程，司机收入还未操作，需要知道平台怎么收费
            /*--------保存司机本单行驶距离--------*/
            /*--------更新结算日志--------*/
            $data_pay_log ['off_car_local'] = $off_local;
            $data_pay_log ['off_car_name'] = $actual['province'].$actual['city'].$actual['district'].$actual['place_name'];
            db('pay_log')->where("common_id=$common_id AND driver_id=$id")->update($data_pay_log);
            /*--------更新结算日志--------*/
            return array('common_id'=>$common_id,'order_type'=>$order_type,'order_status'=>$data['order_status']);
        }
        return array('status'=>0,'msg'=>'请勿重复点击');//订单状态错误
    }

    /**
     * 此方法已不使用，对应接口由Java编写
     * 确认乘客上车选择保存实时位置的表名，并保存此时的位置信息
     * @param $id
     * @param $common_id
     * @param $local
     * @param $direction
     * @return array
     * */
    public function localFirst($id,$common_id,$local,$direction)
    {
        $orderModel = new OrderModel();
        $field = 'on_car_time,local_table,order_status,order_type';
        $order_info = $orderModel->getOrderById($common_id,$field);
        if($order_info['order_status']==20){//订单应处于未上车状态
            /*$data_order['local_table'] = $this->getLiveLocalTable();*/
            $data['created_at'] = $data_order['on_car_time'] = time();
            $data_order['common_id'] = $common_id;
            $data_order['order_status'] = 30;//已上车
            db('order_common')->update($data_order);
            $data['live_local'] = $local;
            $data['driver_id'] = $id;
            $data['common_id'] = $common_id;
            $data['distance'] = 0;
            $data['direction'] = $direction;
            db($order_info['local_table'])->insert($data);
            $cache_name = 'live_local_'.$id.'_'.$common_id;
            $options = array(
                // 缓存类型为File
                'type'   => 'File',
                //0为 缓存有效期为永久有效
                'expire' => 12*60*60,
                // 指定缓存目录
                'path'   => config('live_local_cache_path'),
            );
            cache($cache_name,$local,$options);
            return array('common_id'=>$common_id,'order_status'=>$data_order['order_status']);
        }
        return array('status'=>0);
    }

    /**
     * 获取记录订单实时位置的表名
     * @return string
     * */
    public function getLiveLocalTable()
    {
        $LLTL = db('live_local_table_list');
        $tripModel = new TripModel();
        $name = $LLTL->order('id desc')->field('name')->find();
        if($name){
            $count = db($name)->count();
            if($count>=Define::MAXRECORDS){
                $sn = substr($name,strrpos($name,'_')+1);
                $sn++;
                $name = $data['name'] = "live_local_".$sn;
                $tripModel->createLiveLocalTable($name);
                $data['created_at'] = time();
                $LLTL->insert($data);
            }
        }else{
            $name = 'live_local';
            $count = db($name)->count();
            if($count>=Define::MAXRECORDS){
                $data['name'] = $name = "live_local_1";
                $tripModel->createLiveLocalTable($name);
                $data['created_at'] = time();
                $LLTL->insert($data);
            }
        }
        return $name;
    }

    /**
     * 保存乘客下车地点信息
     * @param $id
     * @param $common_id
     * @param $local
     * @param $direction
     * @param $table
     * @param $zone_price//计价标准
     * @param $order_type //订单类型 2为出租车，1为网约车
     * @return array('real_distance','original_price')
     * */
    public function saveOff($id,$common_id,$local,$table,$zone_price,$order_type,$direction)
    {
        $TripModel = new TripModel();
        $map['driver_id'] = $data['driver_id'] = $id;
        $map['order_id'] = $data['order_id'] = $common_id;
        $data['created_at'] = time();
        $local_info = $TripModel->getLiveLocalInfo($table,$map,'id desc','longitude,latitude');
        $distance = Local::getDistance($local_info['longitude'].','.$local_info['latitude'], $local);
        if($distance['status']==0){
            return array("status" => 10);
        }
        $data['distance'] = $distance['data'];
        $data['longitude'] = explode(',',$local)[0];
        $data['latitude'] = explode(',',$local)[1];
        $data['direction'] = $direction;
        $map['status'] = $data['status'] = 2;
        $TripModel->saveLocal($table,$data);
        $return['real_distance'] = db($table)->where($map)->sum('distance');
        $return['original_price'] = $order_type==1 ? calculatePrice($zone_price,$return['real_distance'])['price']:0;
        return $return;
    }

    /*
	 * 订单结算
	 * @param $uid
	 * @param $common_id
	 * @param $need_price
	 * */
    public function checkout($uid,$need_price,$common_id)
    {
        $wallet = new WalletModel();
        $user_wallet = $wallet->getWalletByUid($uid);
        if($need_price>$user_wallet['wallet_money']||empty($user_wallet)){
            //推送跳转用户支付连接充值

            return array('status'=>0);
        }
        $money = '-'.$need_price;
        $wallet->addWallet($uid,$money);
        db('order_common')->where('common_id='.$common_id)->update(array('order_status'=>45));
        //推送跳转用户支付成功

        return array('status'=>1);
    }

    /**
     * 根据司机ID，获取订单信息
     * @param $did
	 * @param $field
	 * @param $p
	 * @param $limit
	 * @param $order
	 * @return false|\PDOStatement|string|\think\Collection
     * */
    public function getTripByDid($did,$field='*',$p=1,$limit=10,$order='common_id desc')
    {
        $tripRecord = new OrderModel();
        return $tripRecord->getOrderList($field,array('driver_id'=>$did),$p,$limit,$order);
    }
}